<template>
  <view class="join-trial-container">
    <view class="card">
      <u-form :labelStyle="labelStyle"  :model="form" ref="uForm" label-width="180rpx" label-align="left">
        <u-form-item required borderBottom label="小区名称" prop="communityName">
          <u-input maxlength="20" border="none" v-model="form.communityName" placeholder="请输入小区名称" />
        </u-form-item>
      
        <u-form-item required borderBottom label="所在省市" prop="region">
          <view class="u-flex" @click="chooseRegion"  >
            <u-input  disabled border="none" v-model="form.region" placeholder="请选择所在省市区（县）"  />
            <u-icon   name="arrow-right" slot="right" size="24" color="#ccc" />
          </view>
        </u-form-item>
        <u-form-item  label="详细地址" >
          <u-input border="none" v-model="form.detailAddress" placeholder="请输入详细地址，例如XX路XX号"  />
        </u-form-item>
        
      </u-form>
    </view>

    <view class="card">
      <view class="section-title">申请人信息</view>
      <u-form  :labelStyle="labelStyle" :model="form" ref="uForm2" label-width="180rpx" label-align="left">
        <u-form-item required borderBottom label="申请人姓名" prop="applyName">
          <u-input maxlength="10" v-model="form.applyName" placeholder="请输入您的真实姓名" border="none" />
        </u-form-item>
        <u-form-item required borderBottom label="手机号码" prop="mobile">
          <u-input type="number" v-model="form.mobile" placeholder="请输入您的手机号码" border="none" />
         
        </u-form-item>
        <!-- <view class="form-tip">同一个号码只能注册一个公司</view> -->
        <!-- <u-form-item borderBottom label="短信验证码" prop="code">
          <view style="flex:1;display:flex;align-items:center;position:relative;">
            <u-input
              v-model="form.code"
              placeholder="请输入短信验证码"
              border="none"
              maxlength="6"
              style="flex:1;"
            />
            <view
              class="code-btn"
              :class="{disabled: countdown>0}"
              @click=" getCode()"
            >
              <template v-if="countdown === 0">获取验证码</template>
              <template v-else>{{ countdown }}s</template>
            </view>
          </view>
        </u-form-item> -->
        <u-form-item required borderBottom label="小区组织状态" prop="applyType">
          <view class="u-flex" @click="chooseApplyType">
            <u-input disabled border="none" v-model="form.applyTypeName" placeholder="请选择小区组织状态"  />
            <u-icon name="arrow-right" slot="right" size="24" color="#ccc" />
          </view>
        </u-form-item>
        <u-form-item required borderBottom label="申请原因" prop="applyReason">
          <view class="u-flex" @click="chooseApplyReason">
            <u-input disabled border="none" v-model="applyReasonText" placeholder="请选择申请原因"  />
            <u-icon name="arrow-right" slot="right" size="24" color="#ccc" />
          </view>
        </u-form-item>
        <!-- <u-form-item required borderBottom label="申请人类型" prop="applyPersonType">
          <view class="u-flex" @click="chooseApplyPersonType">
            <u-input disabled border="none" v-model="applyPersonTypeText" placeholder="请选择申请人类型"  />
            <u-icon name="arrow-right" slot="right" size="24" color="#ccc" />
          </view>
        </u-form-item> -->
        <!-- <u-form-item required borderBottom label="申请人身份" prop="applyPersonRole">
          <view class="u-flex" @click="chooseApplyPersonRole">
            <u-input disabled border="none" v-model="applyPersonRoleText" placeholder="请选择申请人身份"  />
            <u-icon name="arrow-right" slot="right" size="24" color="#ccc" />
          </view>
        </u-form-item> -->
        <u-form-item required borderBottom label="了解方式" prop="method">
          <view class="u-flex" @click="chooseMethod">
            <u-input disabled border="none" v-model="methodText" placeholder="请选择了解方式"  />
            <u-icon name="arrow-right" slot="right" size="24" color="#ccc" />
          </view>
        </u-form-item>
        <u-form-item borderBottom label="楼栋数" prop="buildNum">
          <u-input type="number" border="none" v-model="form.buildNum" placeholder="请输入楼栋数" />
        </u-form-item>
        <u-form-item borderBottom label="户数" prop="roomNum">
          <u-input type="number" border="none" v-model="form.roomNum" placeholder="请输入户数" />
        </u-form-item>
        <u-form-item  label="组织证明材料(盖章)" label-width="250rpx" prop="pictureUrl">
        </u-form-item>
          <view class="cert-tip">(填写后我们将在2个工作日内完成认证审核，认证后将可使用投票决议、房屋业主管理等高级功能)</view>
        <view class="cert-upload">
            <Upload v-model="form.pictureUrl" max-count="5" @afterRead="afterRead"/>
          </view>
      </u-form>
    </view>

    <!-- <view class="agreement-check u-flex u-row-left" style="margin: 32rpx 0 120rpx 0;">
      <u-checkbox @change="agreeCheckedChange" v-model="agreeChecked"  name="agreeChecked" activeColor="#0030a7" size="18"></u-checkbox>
      <text style="margin-left: 8rpx; font-size: 28rpx; color: #333;">
        我已阅读并同意
        <text class="link"  @click="goToPlatformAgreement">《平台服务协议》</text>
      </text>
    </view> -->

    <view class="fixed-bottom-btn-wrap">
      <view class="submit-btn" @click="submit">申请入驻</view>
    </view>

    <!-- 地区选择器 -->
    <u-picker 
     :immediateChange="true"
      :show="showRegionPicker" 
      ref="regionPicker"
      :columns="regionColumns" 
      @confirm="onRegionConfirm"
      @cancel="showRegionPicker = false"
      @change="onRegionChange"
      title="选择地区"
    ></u-picker>

    <!-- 申请类型选择器 -->
    <u-picker 
      :show="showApplyTypePicker" 
      ref="applyTypePicker"
      :columns="[applyTypeOptions]" 
      @confirm="onApplyTypeConfirm"
      @cancel="showApplyTypePicker = false"
      title="选择小区组织状态"
    ></u-picker>
    <!-- 申请原因选择器 -->
    <u-picker 
      :show="showApplyReasonPicker" 
      ref="applyReasonPicker"
      :columns="[applyReasonOptions]" 
      @confirm="onApplyReasonConfirm"
      @cancel="showApplyReasonPicker = false"
      title="选择申请原因"
    ></u-picker>
    <!-- 申请人类型选择器 -->
    <u-picker 
      :show="showApplyPersonTypePicker" 
      ref="applyPersonTypePicker"
      :columns="[applyPersonTypeOptions]" 
      @confirm="onApplyPersonTypeConfirm"
      @cancel="showApplyPersonTypePicker = false"
      title="选择申请人类型"
    ></u-picker>
    <!-- 申请人身份选择器 -->
    <u-picker 
      :show="showApplyPersonRolePicker" 
      ref="applyPersonRolePicker"
      :columns="[applyPersonRoleOptions]" 
      @confirm="onApplyPersonRoleConfirm"
      @cancel="showApplyPersonRolePicker = false"
      title="选择申请人身份"
    ></u-picker>
    <!-- 了解方式选择器 -->
    <u-picker 
      :show="showMethodPicker" 
      ref="methodPicker"
      :columns="[methodOptions]" 
      @confirm="onMethodConfirm"
      @cancel="showMethodPicker = false"
      title="选择了解方式"
    ></u-picker>
  </view>
</template>

<script>
import {addCommunityApply,getAreas} from '@/api'
import Upload from '@/components/upload/index.vue'
import ls from '@/util/ls'
export default {
  components: {
    Upload
  },
  data() {
    return {
      form: {
        applyPersonType:"1",
        communityName: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        detailAddress: '',
        applyName: '',
        mobile: '',
        code: '',
        applyType: '',
        pictureUrl: [],
        applyTypeName:"",
        applyReason: '',
        applyPersonRole: '',
        method: '',
        buildNum: '',
        roomNum: '',
      },
      countdown: 0,
      timer: null,
      labelStyle: {
        fontSize: '26rpx',
      
      },
      // 地区选择器相关
      showRegionPicker: false,
      regionColumns: [[], [], []], // 省市区三列数据
      regionData: [], // 原始地区数据
      selectedRegion: {
        province: '',
        city: '',
        area: '',
        provinceCode: '',
        cityCode: '',
        areaCode: ''
      },
      // 申请类型选择器相关
      showApplyTypePicker: false,
      applyTypeOptions: [
        { text: '预组建', value: '1' },
        { text: '筹备组', value: '2' },
        { text: '业委会', value: '3' },
        { text: '其他', value: '4' }
      ],
      // 申请原因选择器相关
      showApplyReasonPicker: false,
      applyReasonOptions: [
        { text: '成立业委会', value: '1' },
        { text: '业委会换届', value: '2' },
        { text: '罢免业委会', value: '3' },
        { text: '解聘／续聘／选聘物业', value: '4' },
        { text: '其他', value: '99' }
        // { text: '使用／筹集专项维修资金', value: '5' },
        // { text: '公共收益分配', value: '6' },
        // { text: '发起调查问卷', value: '7' },
        // { text: '小区财务管理', value: '9' },
        // { text: '其他', value: '99' }
      ],
      // 申请人类型选择器相关
      showApplyPersonTypePicker: false,
      applyPersonTypeOptions: [
        { text: '小区人员（业委会／筹备组／物业／第三方公司）', value: '1' },
        // { text: '政府人员（社区／街道）', value: '2' },
     
      ],
      // 申请人身份选择器相关
      showApplyPersonRolePicker: false,
      applyPersonRoleOptions: [
        { text: '物业人员', value: '1' },
        { text: '志愿者业主', value: '2' }
      ],
      // 了解方式选择器相关
      showMethodPicker: false,
      methodOptions: [
        { text: '搜索', value: '1' },
        { text: '公众号', value: '2' },
        { text: '短视频', value: '3' },
        // { text: '其他自媒体(小红书/知乎等)', value: '4' },
        { text: '他人推荐', value: '5' },
        // { text: '其它', value: '6' }
      ],
      agreeChecked: false,
    }
  },
  onLoad(){
    this.init()
  },
  methods: {
    agreeCheckedChange(e){
      
      this.agreeChecked=e
    },
    async init(){
      let res = await getAreas({})
   
      this.regionData = res.rows || []
      this.initRegionColumns()
    },
    
    // 初始化地区选择器数据
    initRegionColumns() {
      // 第一列：省份
      const provinces = this.regionData.map(province => ({
        text: province.name,
        value: province.id
      }))
      
      // 第二列：默认选择第一个省份的城市
      const cities = this.regionData[0]?.children?.map(city => ({
        text: city.name,
        value: city.id
      })) || []
      
      // 第三列：默认选择第一个城市的区县
      const areas = this.regionData[0]?.children?.[0]?.children?.map(area => ({
        text: area.name,
        value: area.id
      })) || []
      
      this.regionColumns = [provinces, cities, areas]
    },
    
    // 地区选择器变化事件
    onRegionChange(e) {
      const { columnIndex, index } = e
      
      if (columnIndex === 0) {
        // 省份变化，更新城市列表
        const selectedProvince = this.regionData[index]
        const cities = selectedProvince?.children?.map(city => ({
          text: city.name,
          value: city.id
        })) || []
        
        // 更新城市列
        this.$refs.regionPicker.setColumnValues(1, cities)
        
        // 同时更新区县列为第一个城市的区县
        const firstCity = selectedProvince?.children?.[0]
        const areas = firstCity?.children?.map(area => ({
          text: area.name,
          value: area.id
        })) || []
        this.$refs.regionPicker.setColumnValues(2, areas)
        
      } else if (columnIndex === 1) {
        // 城市变化，更新区县列表
        const provinceIndex = this.$refs.regionPicker.getIndexs()[0]
        const selectedProvince = this.regionData[provinceIndex]
        const selectedCity = selectedProvince?.children?.[index]
        const areas = selectedCity?.children?.map(area => ({
          text: area.name,
          value: area.id
        })) || []
        
        // 更新区县列
        this.$refs.regionPicker.setColumnValues(2, areas)
      }
    },
    
    // 地区选择器确认事件
    onRegionConfirm(e) {
  
      const [provinceIndex, cityIndex, areaIndex] = e.indexs
      const [province, city, area] = e.value
      
      // 更新表单数据
      this.selectedRegion = {
        province: province.text,
        city: city.text,
        area: area.text,
        provinceCode: province.value,
        cityCode: city.value,
        areaCode: area.value
      }
      
      // 更新显示文本
      this.form.region = `${province.text} ${city.text} ${area.text}`
      
      // 更新表单中的地区代码
      this.form.provinceCode = province.value
      this.form.cityCode = city.value
      this.form.areaCode = area.value
      
      this.showRegionPicker = false
    },
    
    chooseRegion() {
      this.showRegionPicker = true
    },
    
    chooseApplyType() {
      this.showApplyTypePicker = true
    },
    
    onApplyTypeConfirm(e) {
      const selectedType = e.value[0]

      this.form.applyType = Number(selectedType.value)
      this.form.applyTypeName = selectedType.text
      this.showApplyTypePicker = false
    },
    
    getCode() {
      if (!this.form.mobile) {
        this.$u.toast('请先输入手机号');
        return;
      }
      // 这里应调用短信验证码接口
      this.countdown = 60;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timer);
        }
      }, 1000);
    },
    afterRead(file) {
      this.form.pictureUrl = [file];
    },
    /**
     * 批量赋值表单字段
     * @param {Object} data 后端返回的数据对象，字段需与 form 对应
     * 用法示例：this.setFormData(data)
     */
    setFormData(data) {
      Object.assign(this.form, data)
    },
    goToPlatformAgreement() {
      uni.navigateTo({
        url: '/pages/platformagreement/index'
      })
    },
    // 手机号格式校验
    validatePhone(phone) {
      const phoneReg = /^1[3-9]\d{9}$/
      return phoneReg.test(phone)
    },
    
    submit() {
      let agreeChecked=this.agreeChecked
   
      let user=ls.get('user')
     
      let from=uni.$u.deepClone(this.form)
      if(from.applyPersonType==""){
        from.applyPersonType="1"
      }
   
       const {communityName,region,detailAddress,applyName,mobile,applyType,pictureUrl}=from
        if(!from.communityName){
          uni.$u.toast('请输入小区名称')
          return
        }
        if(!from.applyName){
          uni.$u.toast('请输入申请人姓名')
          return
        }
        if(!from.mobile){
          uni.$u.toast('请输入手机号码')
          return
        }
        if(!this.validatePhone(from.mobile)){
          uni.$u.toast('请输入正确的手机号码')
          return
        }
        if(!from.applyPersonType){
          uni.$u.toast('请选择申请人类型')
          return
        }
        // if(!from.applyPersonRole){
        //   uni.$u.toast('请选择申请人身份')
        //   return
        // }
        if(!from.applyReason){
          uni.$u.toast('请选择开通原因')
          return
        }
        // if(!this.agreeChecked){
        //   uni.$u.toast('请先阅读并同意平台服务协议')
        //   return
        // }
      from.pictureUrl=from.pictureUrl.join(',')
      if(user.wxUser){
        from.userId=user.wxUser.wxUserId
      }
   
      addCommunityApply(from).then(res => {
         uni.$u.toast('申请提交成功')
         let t=setTimeout(() => {
          uni.reLaunch({
            url:'/pages/joinTrialok/index'
          })
          clearTimeout(t)
         }, 1000)
        
      })
      // 表单校验与提交逻辑
    },
    chooseApplyReason() {
      this.showApplyReasonPicker = true;
    },
    onApplyReasonConfirm(e) {
      const selected = e.value[0];
      this.form.applyReason = selected.value;
      this.showApplyReasonPicker = false;
    },
    chooseApplyPersonType() {
      this.showApplyPersonTypePicker = true;
    },
    onApplyPersonTypeConfirm(e) {
      const selected = e.value[0];
      this.form.applyPersonType = selected.value;
      this.showApplyPersonTypePicker = false;
    },
    chooseApplyPersonRole() {
      this.showApplyPersonRolePicker = true;
    },
    onApplyPersonRoleConfirm(e) {
      const selected = e.value[0];
      this.form.applyPersonRole = selected.value;
      this.showApplyPersonRolePicker = false;
    },
    chooseMethod() {
      this.showMethodPicker = true;
    },
    onMethodConfirm(e) {
      const selected = e.value[0];
      this.form.method = selected.value;
      this.showMethodPicker = false;
    },
  },
  computed: {
    applyReasonText() {
      const found = this.applyReasonOptions.find(item => item.value == this.form.applyReason);
      return found ? found.text : '';
    },
    applyPersonTypeText() {
      const found = this.applyPersonTypeOptions.find(item => item.value == this.form.applyPersonType);
      return found ? found.text : '';
    },
    applyPersonRoleText() {
      const found = this.applyPersonRoleOptions.find(item => item.value == this.form.applyPersonRole);
      return found ? found.text : '';
    },
    methodText() {
      const found = this.methodOptions.find(item => item.value == this.form.method);
      return found ? found.text : '';
    }
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
  }
}
</script>

<style lang="scss" scoped>
.join-trial-container {
  padding: 32rpx 24rpx 120rpx 24rpx;
  background: #f5f7fa;
  min-height: 100vh;
  .link{
    color: $uni-color-primary;
    text-decoration: underline;
  }
}
.card {
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(0,0,0,0.04);
  padding: 24rpx 32rpx 32rpx 32rpx;
  margin-bottom: 32rpx;
}
.section-title {
  font-size: 26rpx;

  margin: 0 0 24rpx 0;
  color: #222;
}
.form-tip {
  font-size: 22rpx;
  color: #bbb;
  margin: -24rpx 0 24rpx 180rpx;
}
.cert-upload {
  margin-top: 16rpx;
}
.cert-tip {
  font-size: 26rpx;
  color: #bbb;
 
}
.fixed-bottom-btn-wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f5f7fa;
  padding: 24rpx 24rpx 32rpx 24rpx;
  z-index: 99;
}
.submit-btn {
  width: 100%;
  font-size: 34rpx;
  height: 88rpx;
  border-radius: 44rpx;
  background: $uni-color-primary;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx 0 rgba(77, 124, 255, 0.12);
  font-weight: bold;
}
.code-btn {
  margin-left: 24rpx;
  padding: 0 28rpx;
  width: 100px;
  height: 56rpx;
  display: flex;
  align-items: center;
  background: $uni-color-primary;
  color: #fff;
  border-radius: 10rpx;
  font-size: 26rpx;
  transition: background 0.2s;
  user-select: none;
  position: absolute;
  right: 32rpx;
  z-index: 10000;
  
}
.code-btn.disabled {
  background: #b3cfff;
  color: #fff;
}
</style>
<style lang="scss">
.u-input{
  background: rgba(0,0,0,0.0) !important;
}
</style>